package intercept;

import Controller.InterceptInterface;
import information.Information;
import util.HandlerInvoke;
import util.InitMap;

import java.util.Iterator;
import java.util.List;

/**
 *
 */
public class HandlerExecutionChain {
    private static List<InterceptInterface> list= InitMap.getList();
    private static Iterator<InterceptInterface> iterator;
    private boolean flag = false;

    //存放有调用方法的完整信息的对象
    private Information information=null;
    public void setInformation(Information information) {
        this.information = information;
        iteratorFun();
    }

    private static void iteratorFun(){
        //每请求一次就更新迭代器
         iterator = list.iterator();
    }

    //设为单例
    private HandlerExecutionChain(){}

    private static HandlerExecutionChain handlerExecutionChain=null;
    public static HandlerExecutionChain getHandlerExecutionChain(){
        if(handlerExecutionChain==null){
            handlerExecutionChain = new HandlerExecutionChain();
        }
        return handlerExecutionChain;
    }

    public void handler() {
        flag=true;
        InterceptInterface interceptInterface = null;
        if (iterator.hasNext()) {
            interceptInterface = iterator.next();
            interceptInterface.before();
            flag = false;
            interceptInterface.doFilter(this);
            // 下面的代码是在回调完后整体执行的
            // 1.遇到拦截就会设置那么被拦截的不会做调用after()的方法而是改flag为true
            // 然后之后就可以一直调用after()
            //2.放行 方法调用也就是判断拦截器是否关闭之前
            if(flag){
                interceptInterface.after();
            }else{
                flag=true;
            }
        } else {
            Object invoke = HandlerInvoke.invoke(information);
        }
    }

    private static Object createClass(String beanname) {
        Object object = null;
        try {
            object = Class.forName(beanname).newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return object;
    }
}
